<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               ref="crud"
               v-model="form"
               :defaults.sync="showColumn"
               :permission="permissionList"
               :page.sync="page"
               :before-open="beforeOpen"
               @sortable-change="sortableChange"
               @row-del="rowDel"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @refresh-change="refreshChange"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @filter="filterChange"
               @sort-change="sortChange"
               @row-dblclick="handleRowDBLClick"
               :upload-after="uploadAfter"            
               @on-load="onLoad">
      <template slot-scope="scope" slot="menu">
        <el-button type="text"
                   size="small"
                   icon="el-icon-download"
                   v-if="permission.tenant_edit"
                   @click.stop="handleDownloadFile">证书
        </el-button>
        <el-button type="text"
                   size="small"
                   icon="el-icon-s-operation"
                   v-if="permission.tenant_edit"
                   @click.stop="handleSetPrivilege(scope.row)">设置权限
        </el-button>
        
      </template>
      <template slot-scope="scope" slot="menuLeft">
       
        <!-- <el-button type="primary"
                   size="small"
                   icon="el-icon-refresh"
                   v-if="permission.tenant_edit"
                   @click.stop="synchronizeSysMenu">推送菜单
        </el-button>
        <el-button type="primary"
                   size="small"
                   icon="el-icon-refresh"
                   v-if="permission.tenant_edit"
                   @click.stop="synchronizeSysApi">推送接口
        </el-button> -->
        <el-button type="primary"
                   size="small"
                   icon="el-icon-refresh"
                   v-if="permission.tenant_edit"
                   @click.stop="openPushBaseDialog">推送基础数据
        </el-button>
        <el-button type="primary"
                   size="small"
                   icon="el-icon-refresh"
                   v-if="permission.tenant_edit"
                   @click.stop="createAdminUser">创建管理员
        </el-button>
        <el-button type="primary"
                   size="small"
                   icon="el-icon-refresh"
                   v-if="permission.tenant_edit"
                   @click.stop="resetAdminPassword">重置管理员密码
        </el-button>
        <el-button type="primary"
                   size="small"
                   icon="el-icon-key"
                   v-if="permission.tenant_edit"
                   @click.stop="generateLicense">生成租户秘钥
        </el-button>
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   v-if="permission.tenant_delete"
                   @click.stop="handleDelete">删 除
        </el-button>
      </template>
      <template slot="menuRight">
<el-button type="default" v-if="permission.tenant_download" @click.stop="exportExcel"  title="下载" icon="el-icon-download" circle size="small"></el-button>
       </template>
    </avue-crud>
    
    <!-- 
      设置租户权限
     -->
    <el-dialog :title="dialogTitle" width='40%' :close-on-click-modal='false' :visible.sync="setPrivilegeDialog">
      <div v-if="fullscreenLoading" style="width:100%; text-align:center;font-size:30px;top:150px;position:absolute;z-index:5000">
        <i  class="el-icon-loading"></i>
      </div>
      <el-tabs @tab-click="changeTreeTabs" v-model="activeTabName" type="border-card">
        <el-tab-pane label="菜单权限" name="menuPrivilege">
          <el-tree  
            style="height:300px;overflow:auto;"
            :data="menuTreeData"
            :show-checkbox="userInfo.tenantId == 'DOOL1001'"
            :expand-on-click-node='false'
            check-on-click-node = 'true'
            check-strictly="true"
            node-key="id"
            ref="menuTree"
            highlight-current
            :default-checked-keys="treeValue"
            @check="getCheckedNodes"
            :props="menuTreeProps">
          </el-tree>
        </el-tab-pane>
        <el-tab-pane label="接口权限" name="interfacePrivilege">
          <el-tree  
            style="height:300px;overflow:auto;"
            :data="interfaceData"
            :show-checkbox="userInfo.tenantId == 'DOOL1001'"
            :expand-on-click-node='false'
            check-on-click-node = 'true'
            node-key="id"
            ref="interfaceTree"
            highlight-current
            :default-checked-keys="treeValue"
            :props="interfaceTreeProps">
          </el-tree>
        </el-tab-pane>
      </el-tabs> 
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" id="copyBtn" @click="handleSavePrivilege($event)" icon="el-icon-check">保 存</el-button>
        <el-button size="small" @click="setPrivilegeDialog = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 推送基础数据 -->
    <el-dialog :title="pushBaseOption.title" width='800px' :close-on-click-modal='false' :visible.sync="pushBaseOption.showPushBaseDialog">
      <el-transfer
        filterable
        :filter-method="filterMethod"
        filter-placeholder="请输入模块名称"
        :titles="['未选择模块', '已选择模块']"
        v-model="pushBaseOption.selectData"
        :data="pushBaseOption.moduleData">
      </el-transfer>
      <div slot="footer" class="dialog-footer">
        <el-button v-loading="pushBaseOption.pushLoading" size="small" type="primary" id="copyBtn" @click="pushBaseData($event)" icon="el-icon-check">推 送</el-button>
        <el-button size="small" @click="cancelPushBaseData">取 消</el-button>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
import {querySysApiScopeTree,synchronizeSysApiScope} from '@/api/system/sysApiScopeApi';
import {querySysMenuTree,synchronizeSysMenu} from '@/api/system/sysMenuApi';
import {createAdminUser,restAdminPassword   } from '@/api/system/sysUserInfoApi';
import {saveOrUpdateSysTenantPrivilegeRelationList,querySysTenantPrivilegeRelationListPage} from '@/api/system/sysTenantPrivilegeRelationApi';
import {querySysModuleConfigInfoListPage, pushBaseData} from '@/api/system/sysModuleConfigInfoApi';
import {exportSysTenantInfoExcel,generateLicense,saveOrUpdateSysTenantInfo,saveOrUpdateSysTenantInfoList,saveSysTenantInfo,saveSysTenantInfoList,deleteSysTenantInfo,querySysTenantInfo,querySysTenantInfoListPage,updateSysTenantInfo,deleteSysTenantInfoList} from '@/api/system/sysTenantInfoApi';
import {mapGetters} from 'vuex';
import { reqCommonMsg } from '@/util/reqCommonMsg';
import {filterFormat} from '@/util/util';
import {getToken} from '@/util/auth'
import {Base64} from 'js-base64';
import NProgress from 'nprogress'
export default {
  data() {
    return {
      // 控制复制基础数据变量
      pushBaseOption: {
        showPushBaseDialog: false,
        title: '推送基础数据',
        moduleData: [],
        moduleData: [],
        selectData: [],
        pushLoading: false
      },

      //选择框长度控制变量
      checkedLen:0,

      fullscreenLoading: false,
      setPrivilegeDialog: false,
      activeTabName: 'menuPrivilege',
      menuTreeData: [],
      menuTreeProps: {
        children: 'children',
        label: 'name'
      },
      interfaceData: [],
      interfaceTreeProps:  {
        label: 'interfaceName'
      },
      treeValue: [],
      oldTreeValue: [],
      isTabChange: false,
      currentTabName: '',
      dialogTitle: '',

      importDataArea: '',
      form: {},
      selectionList: [],
      loading: true, 
      showColumn: [],
      option: {
        labelPosition: 'right',
        labelSuffix: '：',
        labelWidth: 130,
        dialogTop: '50',
        indexFixed:true, 
        stripe:true,
        calcHeight: 80,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        selection: true,
        addBtn: true,
        viewBtn: false,
        delBtn: true,
        cancelBtn: true,
        printBtn:false,
        saveBtn: true,
        filterBtn:true,          
        menuWidth: 270,
        dialogMenuPosition: 'center',
        dialogDirection:'rtl',
        dialogType:'dialog',
        dialogFullscreen:false,
        dialogClickModal:false,
        dialogWidth: '70%',
        highlightCurrentRow:  true,
        searchShow:true,
        sortable: true,
        column: [
          {
            label: '租户ID',
            prop: 'userTenantId', 
            type: 'select', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '租户名称',
            prop: 'tenantName', 
            type: 'input', 
            search: true,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '联系人名',
            prop: 'contactName', 
            type: 'input', 
            search: true,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '联系电话',
            prop: 'contactPhoneNo', 
            type: 'input', 
            search: true,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [
              {
                required:  true,
                message: '请输入内容',
                trigger: 'blur'
              },
              {
                // 检查手机号
                validator: (rule, value, callback) => {
                  if(value != '' && !this.$validate.isMobile(value)){
                    callback(new Error('请输入11位手机号码！'));
                  }
                  else{
                    callback();
                  }
                }
              }
            ],
            dicData:[]
          },
          {
            label: '联系地址',
            prop: 'contactAddress', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '绑定域名',
            prop: 'bindDomainName', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '管理登录ID',
            prop: 'clientId', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            disabled: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '客户秘钥',
            prop: 'custSecretKey', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '默认密码',
            prop: 'defaultPassword', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            disabled: true,
            overHidden: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '系统版本号',
            prop: 'systemVersionNo', 
            type: 'number', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            maxRows: 999999999,
            minRows: 1,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '菜单版本号',
            prop: 'menuVersionNo', 
            type: 'number', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            maxRows: 999999999,
            minRows: 1,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '顶部菜单版本号',
            prop: 'topMenuVersionNo', 
            type: 'number', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            maxRows: 999999999,
            minRows: 1,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '重置编号',
            prop: 'resetNo', 
            type: 'number', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            maxRows: 999999999,
            minRows: 1,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '消息版本编号',
            prop: 'msgNo', 
            type: 'number', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            maxRows: 999999999,
            minRows: 1,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '通知消息内容',
            prop: 'noticeMsg', 
            type: 'textarea', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 24,
            sortable: false,
            hide: true,
            overHidden: true,
            maxRows:3,
            minRows:2,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          // {
          //   label: '系统登录颜色',
          //   prop: 'defaultSystemColor', 
          //   type: 'color', 
          //   search: false,
          //   searchMmultiple: false,
          //   searchLabelWidth: 100,
          //   multiple: false,
          //   span: 12,
          //   sortable: false,
          //   hide: true,
          //   value: 'blue',
          //   overHidden: true,
          //   rules: [{
          //     required:  false,
          //     message: '请输入内容',
          //     trigger: 'blur'
          //   }],
          //   dicData:[]
          // },
          {
            label: '系统首页背景',
            prop: 'bgImgUrl', 
            type: 'upload', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            value: 'blue',
            overHidden: true,
            listType: 'picture-img',
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            propsHttp: {
              name: 'fileName',
              url: 'filePath'
            },
            tip: '文件大小不超过10M',
            action: '/file/upload',
          },
          {
            label: '登录框背景',
            prop: 'loginBgUrl', 
            type: 'upload', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            value: 'blue',
            overHidden: true,
            listType: 'picture-img',
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            propsHttp: {
              name: 'fileName',
              url: 'filePath'
            },
            tip: '文件大小不超过10M',
            action: '/file/upload',
          },
          {
            label: '公司LOGO',
            prop: 'logoUrl', 
            type: 'upload', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            value: 'blue',
            overHidden: true,
            listType: 'picture-img',
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            propsHttp: {
              name: 'fileName',
              url: 'filePath'
            },
            tip: 'ICO类型文件',
            action: '/file/upload',
          },
          {
            label: '公司大LOGO',
            prop: 'bigLogoUrl',
            type: 'upload',
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            value: 'blue',
            overHidden: true,
            listType: 'picture-img',
            rules: [{
              required: false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            propsHttp: {
              name: 'fileName',
              url: 'filePath'
            },
            tip: 'ICO类型文件',
            action: '/file/upload',
          },
          {
            label: '购买方式',
            prop: 'buyWay', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '账户余额',
            prop: 'acctBal', 
            type: 'number', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            maxRows: 999999999,
            minRows: 1,
            value:'0',
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '生效日期',
            prop: 'effectDate', 
            type: 'date', 
            format:'yyyy-MM-dd',
            valueFormat: 'yyyy-MM-dd',
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '失效日期',
            prop: 'invalidDate', 
            type: 'date', 
            format:'yyyy-MM-dd',
            valueFormat: 'yyyy-MM-dd',
            value: '2099-12-31',
            pickerOptions: {
              disabledDate(time) {
                return time.getTime() <= Date.now();
              }
            },
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '有效标志',
            prop: 'validFlag', 
            type: 'switch', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            value: '1',
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[
              {
                label:'失效',
                value:'0'
              },{
                label:'生效',
                value:'1'
              }
            ]
          },
          {
            label: '许可证参数',
            prop: 'licenseContent', 
            type: 'textarea', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 24,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[
            ]
          },
        ]
      },
      data: [],
      // 请求参数区
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      reqParams: {
        singleBody: {},
        listBody: [{}],
        sqlCondition:[],
        orderRule: {},
        currentPage: 1,
        pageSize: 10
      },
      commonData: null,
      conditions: [],
      orderRules: [],
      singleBody: {}
    };
  },
  computed: {
    ...mapGetters(['website','userInfo','permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.tenant_add, false),
        viewBtn: this.vaildData(this.permission.tenant_view, false),
        delBtn: this.vaildData(this.permission.tenant_delete, false),
        editBtn: this.vaildData(this.permission.tenant_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push({id : ele.id});
      });
      return ids;
    } 
  },
  methods: { 
    uploadAfter(res, done, loading,column){
      done()
      if(res.head.respCode == 'S0000'){
        this.$message({
          type: 'success',
          message: '上传成功！'
        });
      }
      else{
        this.$message({
          type: 'error',
          message: '上传失败！'
        });
      }
    },
    /**
     * 复选框选择
     */
    getCheckedNodes(arg1,arg2) {
      let superId = this.currentRow.userTenantId+'00000000';
      if(arg2.checkedKeys.length> this.checkedLen){
        this.treeValue.push(arg1.id)
        let _node = this.$refs.menuTree.getNode(arg1.id)
        //递归选中父节点
        let setParentChecked = (arg0,arg1) => {
          let str = ','+arg0.join(',')+','; 
          let parantId = arg1.data.parentId;
          if(parantId != ''&&  parantId != superId && !str.includes(','+parantId+',')){
            arg0.push(parantId)
            setParentChecked(arg0,this.$refs.menuTree.getNode(parantId));
          }
        }
        setParentChecked(this.treeValue,_node);
        //递归选中子节点
        let setChildChecked = (arg0,arg1) => {
          let str = ','+arg0.join(',')+',';
          if(arg1.children.length>0){
            arg1.children.map(item=>{
              if(item.id&&!str.includes(','+item.id+',')){
                arg0.push(item.id);
              }
              setChildChecked(arg0,item);
            });
          }
        }
        setChildChecked(this.treeValue,arg1);
        this.$refs.menuTree.setCheckedKeys(this.treeValue);
      }else if(arg2.checkedKeys.length< this.checkedLen){
        this.treeValue.splice(this.treeValue.indexOf(arg1.id),1);
        //递归取消选中子节点
        let setChildUnChecked = (arg0,arg1) => {
          let str = ','+arg0.join(',')+',';
          if(arg1.children.length>0){
            arg1.children.map(item=>{
              if(str.includes(','+item.id+',')){
                arg0.splice(arg0.indexOf(item.id),1);
              }
              setChildUnChecked(arg0,item);
            });
          }
        }
        setChildUnChecked(this.treeValue,arg1);
        this.$refs.menuTree.setCheckedKeys(this.treeValue);
      }
      this.checkedLen=this.$refs.menuTree.getCheckedKeys().length;
    },
    /**
     * 切换权限标签
     */
    async changeTreeTabs(){
      let resultList = this.changedList();
      if(this.isTabChange && resultList.length > 0){
        await this.$confirm('切换将会丢失之前的改动，需要保存吗?', {
          confirmButtonText: '保存',
          cancelButtonText: '放弃',
          type: 'warning'
        }).then(() => {
          this.handleSavePrivilege();
        }, error => {
          return false;
        }).catch(() => {
          return false;
        }); 
      }
      this.treeValue =[];
      this.oldTreeValue = [];
      this.isTabChange = true;
      this.currentTabName = this.activeTabName;
      this.fullscreenLoading = true;
      if(this.activeTabName == 'menuPrivilege'){
        //获取已选菜单权限
        await this.getCheckedResource('1')
        //获取所有菜单
        await this.getMenuTree();
      }
      else if(this.activeTabName == 'interfacePrivilege'){
        //获取已选接口权限
        await this.getCheckedResource('2')
        //获取所有菜单
        await this.getApiScopeList();
      }
      this.fullscreenLoading = false;
    },
    /**
     * 打开权限设置对话框
     */
    async handleSetPrivilege(row){
      this.dialogTitle = '租户权限设置-['+row.tenantName+']';
      this.setPrivilegeDialog = true;
      this.currentRow = row;
      //获取已选菜单权限
      this.isTabChange = false;
      await this.changeTreeTabs(); 
    },
    /**
     * 获取已选择的资源
     */
    async getCheckedResource(type){
      this.treeValue = [];
      this.singleBody = {
        resourceType : type,
        tenantId: this.currentRow.userTenantId,
      }
      this.reqParams =  {
        singleBody: this.singleBody,
        currentPage: 1, 
        pageSize: this.website.maxPageSize
      }
      this.commonData = reqCommonMsg(this.reqParams)
      await querySysTenantPrivilegeRelationListPage(this.commonData).then(res => {
        res.data.body.listBody.forEach(element => {
          this.treeValue.push(element.resourceId);
        });
        this.oldTreeValue=[];
        this.oldTreeValue = this.deepClone(this.treeValue)
      }, error => {
      });
    },
    /**
     * 获取树形菜单
     */
    async getMenuTree(){
      // 加载树形机构列表
      this.singleBody = {
        tenantId: this.currentRow.userTenantId,
        parentMenuId: this.currentRow.userTenantId+'00000000',
        menuCategory: '2',
        menuLevel: '1'
      }
      this.reqParams =  {
        singleBody: this.singleBody,
        currentPage: 1, 
        pageSize: this.website.maxPageSize
      }
      this.commonData = reqCommonMsg(this.reqParams)
      await querySysMenuTree(this.commonData).then(res => {
        this.singleBody = {};
        this.menuTreeData = res.data.body.listBody; 
      }, error => {
      });
    },
    /**
     * 获取接口列表
     */
    async getApiScopeList(){
      // 加载树形机构列表
      this.singleBody = {
        tenantId: this.currentRow.userTenantId
      }
      this.reqParams =  {
        singleBody: this.singleBody,
        currentPage: 1, 
        pageSize: this.website.maxPageSize
      }
      this.commonData = reqCommonMsg(this.reqParams)
      await querySysApiScopeTree(this.commonData).then(res => {
        this.singleBody = {};
        this.interfaceData = res.data.body.listBody;
      }, error => {
      });
    },
    /**
     * 添加权限记录
     */
    handleSavePrivilege() {
      let resultList = this.changedList();
      if(resultList.length > 0){
        this.reqParams =  {
          transCode: '0001',
          listBody: resultList
        }
        this.commonData = reqCommonMsg(this.reqParams)
        saveOrUpdateSysTenantPrivilegeRelationList(this.commonData).then(() => {
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '保存成功!'
          });
          this.addMenuDialog = false;
          this.fullscreenLoading = false;
          this.oldTreeValue = [];
          this.oldTreeValue = this.deepClone(this.treeValue)
        }, error => {
          //this.$console.log(error);
        });
      }
      else{
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '未发生变化,无需保存!'
        });
        this.fullscreenLoading = false;
      }
    },
    /**
     * 获取变化列表
     */
    changedList(){
      // 判断当前活动tab
      let type = '';
      if(this.currentTabName == 'menuPrivilege'){
        type = '1';
        this.treeValue = this.$refs.menuTree.getCheckedKeys(false);
      }
      else if(this.currentTabName == 'interfacePrivilege'){
        type = '2';
        this.treeValue = this.$refs.interfaceTree.getCheckedKeys(true);
      }
      this.fullscreenLoading = true;
      // 前后选择对比，给新增和删除的打上标识
      let resultList = [];
      // 原列表不存在的表示新增的元素
      let inOldValue = false;
      let inNewValue = false;
      this.treeValue.forEach(element => {
        inOldValue = false;
        for(var i = 0 ; i < this.oldTreeValue.length; i++){
          if (element == this.oldTreeValue[i]) {
            inOldValue = true;
            i = this.oldTreeValue.size + 1;
          }
        }
        //若没找到表示新增元素
        if(!inOldValue){
          resultList.push({
            resourceType: type,
            userTenantId: this.currentRow.tenantId,
            resourceId: element,
            validFlag: '1'
          })
        }
      });

      //新列表中不存在 表示 删除元素
      this.oldTreeValue.forEach(element => {
        inNewValue = false;
        for(var i = 0 ; i < this.treeValue.length; i++){
          if (element == this.treeValue[i]) {
            inNewValue = true;
            i = this.treeValue.size + 1;
          }
        }
        //若没找到表示删除元素
        if(!inNewValue){
          resultList.push({
            resourceType: type,
            userTenantId: this.currentRow.tenantId,
            resourceId: element,
            validFlag: '0'
          })
        }
      });
      return resultList;
    },
    /**
     * 
     */
    /**
     * 加载列表数据
     */
    onLoad(page) {
      this.loading = true;
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage: page.currentPage, 
        pageSize: page.pageSize
      }
      this.commonData = reqCommonMsg(this.reqParams)
      querySysTenantInfoListPage(this.commonData).then(res => {
        
        const data = res.data.body;
        this.page.total = data.total;
        this.data = data.listBody;
        this.loading = false;
        this.selectionClear();
      }, error => {
        this.loading = false; 
      });
    },
    /**
     * 新增一条记录
     */
    rowSave(row, done, loading) {
      this.reqParams.singleBody = row;
      this.commonData = reqCommonMsg(this.reqParams)
      saveSysTenantInfo(this.commonData).then(() => {
        done();
        this.singleBody={};
        this.onLoad(this.page);
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        //this.$console.log('saveSysTenantInfo===>error====>', error)
        //this.$console.log(error);
        loading();
      });         
      //this.$console.log("row = ",row ,loading)
    },
    /**
     * 修改一条记录
     */
    rowUpdate(row, index, done, loading) { 
      this.reqParams.singleBody = row;
      this.commonData = reqCommonMsg(this.reqParams)
      updateSysTenantInfo(this.commonData).then(() => {
        done();
        this.singleBody={}
        this.onLoad(this.page);
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        //this.$console.log(error);
        loading();
      });
      //this.$console.log('loading = ',loading)
    },
    
    /**
     * 同步菜单到租户
     */
    synchronizeSysMenu(){
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一个租户！');
        return;
      }
      this.selectionList.forEach(element => {
        if(element.userTenantId == 'DOOL1001'){
          this.$message.warning('请注意，不能对DOOL1001租户进行同步！');
          throw new Error('请注意，不能对DOOL1001租户进行同步！');
        }
      });
      this.$confirm('同步会覆盖当前租户的所有菜单，确定要同步?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          //批量写入记录
          this.loading=true;
          this.reqParams.listBody = this.selectionList;
          this.commonData = reqCommonMsg(this.reqParams)
          synchronizeSysMenu(this.commonData).then(() => {
            this.loading=false;
            this.$message({
              customClass:'zZindex',
              type: 'success',
              message: '操作成功!'
            });
          }, error => {
            //this.$console.log(error);
            this.loading=false;
            loading();
          });    
        }).catch(() => {});  
    },
    /**
     * 同步接口到租户
     */
    synchronizeSysApi(){
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一个租户！');
        return;
      }
      this.selectionList.forEach(element => {
        if(element.userTenantId == 'DOOL1001'){
          this.$message.warning('请注意，不能对DOOL1001租户进行同步！');
          throw new Error('请注意，不能对DOOL1001租户进行同步！');
        }
      });
      this.$confirm('同步会覆盖当前租户的所有接口，确定要同步?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          //批量写入记录
          this.loading=true;
          this.reqParams.listBody = this.selectionList;
          this.commonData = reqCommonMsg(this.reqParams)
          synchronizeSysApiScope(this.commonData).then(() => {
            this.loading=false;
            this.$message({
              customClass:'zZindex',
              type: 'success',
              message: '操作成功!'
            });
          }, error => {
            //this.$console.log(error);
            this.loading=false;
            loading();
          });    
        }).catch(() => {});  
    },
    /**
     * 创建管理员
     */
    createAdminUser(){
      if (this.selectionList.length !== 1) {
        this.$message.warning('请选择一个租户数据');
        return;
      }
      if (this.selectionList[0].tenantId == this.website.defaultTenantId) {
        this.$message.warning('超级租户不需要创建管理员！');
        return;
      }
      this.reqParams.singleBody = {
        tenantId: this.selectionList[0].tenantId,
        companyName: this.selectionList[0].tenantName,
        mobileNo: this.selectionList[0].contactPhoneNo
      }
      this.commonData = reqCommonMsg(this.reqParams)
      createAdminUser(this.commonData).then(() => {
        this.singleBody={};
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '创建成功!'
        });
      }, error => {
        //this.$console.log(error);
      });
    },
    /**
     * 下载文件
     */
    handleDownloadFile(){
      fetch('/platform/license/downloadLicenseFile', {
        method: 'GET',
        headers: new Headers({
          UserId: this.userInfo.userId,
          remote: 'no',
          UserSign: 'uploadFile',
          Authorization: 'bearer ' + getToken()
        }),
      })
        .then(res => res.blob())
        .then(data => {
          const blobUrl = window.URL.createObjectURL(data);
          const a = document.createElement('a');
          a.download = 'license.lic';
          a.href = blobUrl;
          a.click();
        });
    },
    /**
     * 重置管理员密码
     */
    resetAdminPassword(){
      if (this.selectionList.length !== 1) {
        this.$message.warning('请选择一个租户数据');
        return;
      }
      if (this.selectionList[0].tenantId == this.website.defaultTenantId) {
        this.$message.warning('超级租户不需要修改密码！');
        return;
      }
      this.reqParams.singleBody = {
        tenantId: this.selectionList[0].tenantId
      }
      this.commonData = reqCommonMsg(this.reqParams)
      restAdminPassword(this.commonData).then(() => {
        this.singleBody={};
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '租户管理员密码重置成功（Admin'+this.selectionList[0].tenantId.substring(4,8)+'）!'
        });
      }, error => {
        //this.$console.log(error);
      });
    },
    /**
     * 生成秘钥
     */
    generateLicense(){
      if (this.selectionList.length !== 1) {
        this.$message.warning('请选择一个租户数据');
        return;
      }
      // else if (this.selectionList[0].tenantId == this.website.defaultTenantId) {
      //   this.$message.warning('超级租户不需要创建秘钥！');
      //   return;
      // }
      else if(this.selectionList[0].licenseContent == ''){
        this.$message.warning('租户秘钥参数内容不能为空');
        return;
      }
      this.reqParams.singleBody =  JSON.parse(this.selectionList[0].licenseContent);
      this.commonData = reqCommonMsg(this.reqParams)
      generateLicense(this.commonData).then(() => {
        this.singleBody={};
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '秘钥创建成功!'
        });
      }, error => {
        //this.$console.log(error);
      });
    },
    /*
     * 删除一条记录
     */
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.reqParams.singleBody = row;
          this.commonData = reqCommonMsg(this.reqParams);
          return deleteSysTenantInfo(this.commonData);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
        }).catch(() => {});
    },
    /**
     * 双击打开详细窗口
     */
    handleRowDBLClick (row, event) {
      this.$refs.crud.rowView(row,row.$index);
    },
    /**
     * 批量新增记录
     */
    openBatchAddDialog(){
      this.batchAddDialog = true;
    },
    // 
    handleImport() {
      this.loading=true;
      var dataList = new Array();
      if(this.importDataArea){
        var lineList = this.importDataArea.split('\n')
        lineList.forEach((element,index) => {
          if(element.trim() != ''){
            var field = element.split('\t')
            var fieldList = {
              id:field[0],
              tenantId:field[1],
              userTenantId:field[1],
              tenantName:field[2],
              contactName:field[3],
              contactPhoneNo:field[4],
              contactAddress:field[5],
              bindDomainName:field[6],
              clientId:field[7],
              custSecretKey:field[8],
              defaultSystemColor:field[9],
              defaultPassword:field[10],
              buyWay:field[11],
              acctBal:field[12],
              effectDate:field[13],
              invalidDate:field[14],
            }
            dataList[index] = fieldList
            //this.$console.log('fieldList = ',fieldList)
          }
        });
        //批量写入记录
        this.reqParams.listBody = dataList;
        this.commonData = reqCommonMsg(this.reqParams)
        saveSysTenantInfoList(this.commonData).then(() => {
          this.loading=false;
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
        }, error => {
          //this.$console.log(error);
          this.loading=false;
          loading();
        });      
        //this.$console.log('lineList=',dataList)
      }
      else{
        this.loading=false;
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '数据格式不正确!'
        });
      }
    },
    /**
     * 搜索重置
     */
    searchReset() {
      this.conditions =[];
      this.singleBody = {};
      this.onLoad(this.page);
    },
    /**
     * 搜索
     */
    searchChange(params, done) {
      this.singleBody = params
      this.page.currentPage = 1;
      this.onLoad(this.page);
      done();
    },
    refreshChange(){
      this.onLoad(this.page);
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    /**
     * 处理批量删除
     */
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.reqParams.listBody = this.ids;
          this.commonData = reqCommonMsg(this.reqParams);
          return deleteSysTenantInfoList(this.commonData);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        }).catch(() => {});
    },
    /**
     * 拷贝记录
     */
    handleCopy(row){
      this.$confirm('确定复制数据?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading=true;
        let copyValue=row;
        copyValue.id='0';
        copyValue.dataSign='0'
        copyValue.tableName='拷贝 '+ copyValue.tableName; 
        this.reqParams.singleBody = copyValue;
        this.commonData = reqCommonMsg(this.reqParams)
        saveSysToolTables(this.commonData).then(() => {
          this.singleBody={};
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
          this.loading=false;
        }, error => {
          //this.$console.log(error);
          this.loading=false;
        });
      }).catch(() => {});       
    },
    /**
     * 打开编辑、查询弹窗前查询记录
     */  
    beforeOpen(done, type) {
      this.reqParams =  {
        singleBody: {
          id:this.form.id
        }
      }
      let commonData = reqCommonMsg(this.reqParams)
      if (['edit', 'view'].includes(type)) {
        querySysTenantInfo(commonData).then(res => {
          this.form = res.data.body.singleBody;
        });
      }
      done();
    },
    /**
     * 翻页查询
     */
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    /**
     * 更改每页条数
     */
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    /**
     * 自定义查询条件
     */
    filterChange(result) {
      this.page.currentPage = 1;
      this.conditions = filterFormat(result)
      this.onLoad(this.page);
    },
    /**
     * 列表排序
     */
    sortChange(val){
      this.orderRules=val
      this.onLoad(this.page);
    },
  
    /**
     * 导出Excel
     */
    exportExcel() {
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage:1, 
        pageSize: 100
      }
      //this.$console.log('reqParams = ',this.reqParams)
      this.commonData = reqCommonMsg(this.reqParams)
      exportSysTenantInfoExcel(this.commonData);
    },
    /**
     * 打开复制基础数据dialog
     */
    openPushBaseDialog(){
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一个租户！');
        return;
      }
      this.pushBaseOption.showPushBaseDialog = true;
    },
    /**
     * 获取模块列表
     */
    getModuleList(){
      let reqParams =  {
        singleBody: {},
        listBody: [{}],
        currentPage: 1, 
        pageSize: 1000
      }
      let commonData = reqCommonMsg(reqParams)
      querySysModuleConfigInfoListPage(commonData).then(res => {
        //this.$console.log('res:', res)
        let result = res.data.body.listBody;
        result.map(item => {
          this.pushBaseOption.moduleData.push({
            label: item.moduleName,
            key: item.id
          })
        })
      }, error => {
        
      });
    },
    cancelPushBaseData(){
      this.pushBaseOption.showPushBaseDialog = false;
      this.pushBaseOption.selectData = [];
    },
    /**
     * 推送基础数据
     */
    pushBaseData(event){
      if (this.pushBaseOption.selectData.length === 0) {
        this.$message.warning('请选择模块！');
        return;
      }
      this.pushBaseOption.pushLoading = true;
      let tenantIdList = [];
      this.selectionList.map(item => {
        tenantIdList.push(item.tenantId);
      })
      let reqParams =  {
        singleBody: {
          moduleIdList: this.pushBaseOption.selectData,
          tenantIdList: tenantIdList
        }
      }
      let commonData = reqCommonMsg(reqParams)
      pushBaseData(commonData).then(res => {
        this.pushBaseOption.pushLoading = false;
        this.pushBaseOption.showPushBaseDialog = false;
        this.pushBaseOption.selectData = [];
        this.onLoad(this.page);
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '操作成功, 请2分钟后查看结果！'
        });
      }, error => {
        //this.$console.log(error);
        this.pushBaseOption.pushLoading = false;
      });
    },
    /**
     * 获取系统字典表
     */
    async getSysDict() {
      let dicData = await this.$params.getSysDict('["userTenantId"]')
      this.findObject(this.option.column, 'userTenantId').dicData = dicData.userTenantId
    }
  },
  created() {
    this.getModuleList();
    this.showColumn = this.$getStore({name:  this.userInfo.userId +'sysTenantInfoColumn'});
    //获取系统字典
    setTimeout(() => {
      this.getSysDict();
    }, 1000);
  },
  watch: {
    showColumn: {
      handler(newValue, oldValue) {
        this.$setStore({name:  this.userInfo.userId+'sysTenantInfoColumn', content: this.showColumn});
      },
      deep: true
      //this.$setStore({name: this.userInfo.userId +'sysTenantInfoColumn', content: this.showColumn});
    }
  }
};
</script>
